package lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author jiangwz
 * @create 2019/9/15.
 */
public class ConditionDemo {

    /**
     * 题目 A -> B -> C  分别打印5次,10次,15次
     * 来2轮
     * @param args
     */
    public static void main(String[] args){

        ShareResource shareResource = new ShareResource();


//        for (int i = 0; i < 2; i++) {
//            new Thread(() -> {
//                shareResource.print5();
//            }, "aa").start();
//            new Thread(() -> {
//                shareResource.print10();
//            }, "bb").start();
//            new Thread(() -> {
//                shareResource.print15();
//            }, "cc").start();
//        }


        new Thread(() -> {
            for (int i = 0; i < 2; i++) {
                shareResource.print5();
            }

        }, "aa").start();
        new Thread(() -> {
            for (int i = 0; i < 2; i++) {
                shareResource.print10();
            }

        }, "bb").start();
        new Thread(() -> {
            for (int i = 0; i < 2; i++) {
                shareResource.print15();
            }

        }, "cc").start();


    }
}

class ShareResource {

    volatile int num = 1;// 1=A,2=B,3=C

    ReentrantLock lock = new ReentrantLock();
    Condition a = lock.newCondition();
    Condition b = lock.newCondition();
    Condition c = lock.newCondition();

    public void print5(){
        lock.lock();
        try {
            while (num != 1) {
                a.await();
            }
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + "打印第 " + i);
            }
            num++;
            b.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void print10(){
        lock.lock();
        try {
            while (num != 2) {
                b.await();
            }
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + "打印第 " + i);
            }
            num++;
            c.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void print15(){
        lock.lock();
        try {
            while (num != 3) {
                c.await();
            }
            for (int i = 0; i < 15; i++) {
                System.out.println(Thread.currentThread().getName() + "打印第 " + i);
            }
            num=1;
            a.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}